{
 "cells": [
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-08T07:08:50.513599Z",
     "start_time": "2025-05-08T07:08:50.324883Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "\n",
    "# 定义激活函数和其导数\n",
    "def sigmoid(x):\n",
    "    return 1 / (1 + np.exp(-x))\n",
    "\n",
    "def sigmoid_derivative(x):\n",
    "    return x * (1 - x)\n",
    "\n",
    "# 输入数据\n",
    "inputs = np.array([[0,0],\n",
    "                    [0,1],\n",
    "                    [1,0],\n",
    "                    [1,1]])\n",
    "\n",
    "# 输出数据\n",
    "expected_output = np.array([[0],[1],[1],[0]])\n",
    "\n",
    "# 设置随机数种子\n",
    "np.random.seed(0)\n",
    "\n",
    "# 初始化权重和偏置\n",
    "weights = np.random.rand(2, 1)\n",
    "biases = np.random.rand(1)\n",
    "learning_rate = 0.1\n",
    "epochs = 10000\n",
    "\n",
    "# 训练网络\n",
    "for epoch in range(epochs):\n",
    "    # 前向传播\n",
    "    inputs_dot_weights = np.dot(inputs, weights) + biases\n",
    "    predictions = sigmoid(inputs_dot_weights)\n",
    "\n",
    "    # 计算误差\n",
    "    error = expected_output - predictions\n",
    "    loss = np.mean(error**2)\n",
    "\n",
    "    # 反向传播\n",
    "    d_predicted_output = error * sigmoid_derivative(predictions)\n",
    "\n",
    "    # 更新权重和偏置\n",
    "    inputs_transposed = inputs.T\n",
    "    weights += np.dot(inputs_transposed, d_predicted_output) * learning_rate\n",
    "    biases += np.sum(d_predicted_output, axis=0) * learning_rate\n",
    "\n",
    "    # 打印损失\n",
    "    if epoch % 1000 == 0:\n",
    "        print(f\"Epoch {epoch}, Loss: {np.mean(loss)}\")\n",
    "\n",
    "# 测试网络\n",
    "print(\"Final predictions:\")\n",
    "print(predictions)\n"
   ],
   "id": "1c90572f4cff3eea",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 0, Loss: 0.31751855203891893\n",
      "Epoch 1000, Loss: 0.25000078957232946\n",
      "Epoch 2000, Loss: 0.2500000003028166\n",
      "Epoch 3000, Loss: 0.2500000000001167\n",
      "Epoch 4000, Loss: 0.25000000000000006\n",
      "Epoch 5000, Loss: 0.25\n",
      "Epoch 6000, Loss: 0.25\n",
      "Epoch 7000, Loss: 0.25\n",
      "Epoch 8000, Loss: 0.25\n",
      "Epoch 9000, Loss: 0.25\n",
      "Final predictions:\n",
      "[[0.5]\n",
      " [0.5]\n",
      " [0.5]\n",
      " [0.5]]\n"
     ]
    }
   ],
   "execution_count": 2
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
